package com.example.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

@Configuration
@RequiredArgsConstructor
public class SecurityConfig {

    private final AuthenticationSuccessHandler authenticationSuccessHandler;

    private final AuthenticationFailureHandler authenticationFailureHandler;

    private final LogoutSuccessHandler logoutSuccessHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .formLogin(
                        formLogin -> formLogin
                                .successHandler(authenticationSuccessHandler) // 登录成功处理器
                                .failureHandler(authenticationFailureHandler) // 登录失败处理器
                )
                .logout(
                        logout -> logout
                                .logoutSuccessHandler(logoutSuccessHandler) // 登出成功处理器
                )
                .authorizeHttpRequests(
                        authenticationSuccessHandler -> authenticationSuccessHandler
                                .requestMatchers("/login").permitAll()
                                .anyRequest().authenticated()
                )
                .build();
    }

}
